/*
 * Copyright ShangHai ECLUB Information Technology Co.,Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 * http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.eclub.emotion.rootstone.server.http.mapping;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.eclub.emotion.rootstone.server.context.Global;
import com.eclub.emotion.rootstone.server.deploy.DynamicClassLoader;
import com.eclub.emotion.rootstone.server.http.HttpRequest;
import com.eclub.emotion.rootstone.server.util.Scans;

/**
 * interface to map from URLs to request handler beans. Supports both mapping to
 * bean.
 * 
 * @author jun.yang, Wincor Nixdorf International GmbH
 */
public class RequestHandlerMapping {

	private final Logger LOGGER = Logger.getLogger(RequestHandlerMapping.class);
	private Map<String, ServiceMethodHandler> serviceHandlerMap = new HashMap<String, ServiceMethodHandler>();
	private Pattern patternParam = Pattern.compile("\\{(.+?)\\}");

	public ServiceMethodHandler getHandler(HttpRequest httpRequest) throws Exception {
		String regUrl = getKey(httpRequest.getUri());
		LOGGER.debug("registered URL:" + regUrl);

		if (StringUtils.isEmpty(regUrl)) {
			throw new RuntimeException("Not found regiester URL from HTTP Request");
		}

		return serviceHandlerMap.get(regUrl);
	}

	protected String getKey(String uri) {
		Set<String> set = serviceHandlerMap.keySet();
		for (String reg : set) {
			if (uri.contains(reg)) {
				return reg;
			}
		}
		return null;
	}

	/**
	 * initialize HTTP request mapping
	 * 
	 * @throws Exception
	 */
	public void initialize() throws Exception {
		LOGGER.info("Initialzing HTTP request mapping...");
		serviceHandlerMap.clear();
		StringBuffer sb = new StringBuffer();

		String servicePath = Global.getSingleton().getRootPath() + "service/deploy/" + Global.getSingleton().getServiceConfig().getString("rs.service.name");

		DynamicClassLoader classLoader = new DynamicClassLoader();
		classLoader.addFolder(servicePath);

		serviceHandlerMap = Scans.me().scan(new String[] { servicePath }, classLoader);

		Collections.unmodifiableMap(serviceHandlerMap);
		LOGGER.debug(sb.toString());
		LOGGER.info("finish init http request mapping!");
	}
}
